package cn.zcy.untils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {

    //1. 私有化构造方法
    private JDBCUtils(){}
    //2.声明所需要的配置变量
    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    private static Connection connection;

    //3.提供静态代码块，读取配置文件中的信息为变量赋值，注册驱动
    static {

        try {
            InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties prp=new Properties();
            prp.load(inputStream);
            driverClass=prp.getProperty("jdbc.driver");
            url=prp.getProperty("jdbc.url");
            username=prp.getProperty("jdbc.username");
            password=prp.getProperty("jdbc.password");
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //4.提供获取数据库连接的方法
    public static Connection getConnection(){
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //5.提供释放资源的方法
    public static void close(Connection con, Statement statement, ResultSet resultSet){

        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (con!=null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
